package com.myapp.servlet;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.myapp.sqlmapper.SQLUtil;
import com.myapp.util.CommUtil;
import com.myapp.util.Consts;
import com.myapp.util.DBUtil;
import com.myapp.util.JsonUtil;

public class AddCompany extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -54409255252511560L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		String name = request.getParameter("name");
		String fullName = request.getParameter("fullName");
		String tradeID = request.getParameter("tradeID");
		String desc = request.getParameter("desc");
		String address = request.getParameter("address");
		String createID = request.getParameter("createID");
		if (CommUtil.isBlank(name) || CommUtil.isBlank(tradeID)) {
			String result = CommUtil.setResultInfo(jsonMap, Consts.CHECK_CODE, Consts.ARG_DESCRIBE);
			CommUtil.responseJson(result, response);
			System.out.println("/addCompany 公司名称或所属行业为空 ");
			return;
		}
		List<String> tempList = new ArrayList<String>();
		tempList.add(name);
		String tempSql = SQLUtil.getSql("companyMapper.getCompanyByName", tempList);
		
		Map<String, String> retMap = new HashMap<String, String>();
		try {
			ResultSet rs = DBUtil.exeQuery(tempSql);
			if(rs.next()){
				String result = CommUtil.setResultInfo(jsonMap, Consts.CHECK_CODE, "company.is.exist");
				CommUtil.responseJson(result, response);
				return;
			}
			List<String> paramList = new ArrayList<String>();
			paramList.add(name);
			paramList.add(fullName == null ? "" : fullName);
			paramList.add(tradeID);
			paramList.add(desc == null ? "" : desc);
			paramList.add(address == null ? "" : address);
			paramList.add(createID);
			String insertSql = SQLUtil.getSql("companyMapper.insertCompany", paramList);
			
			DBUtil.exeUpdate(insertSql);

			retMap.put("rescode", Consts.SUCCESS_CODE);
			retMap.put("resmsg", Consts.SUCCESS_DESCRIBE);
			String result = JsonUtil.getJsonStringFromMap(retMap);
			CommUtil.responseJson(result, response);
		} catch (Exception e) {
			e.printStackTrace();
			retMap.put("rescode", Consts.ERROR_CODE);
			retMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			String result = JsonUtil.getJsonStringFromMap(retMap);
			CommUtil.responseJson(result, response);
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		this.doGet(request, response);
	}
}
